package com.mlnx.netty.app.ecg.session.core;


import java.util.concurrent.ConcurrentHashMap;

import io.netty.channel.Channel;

/**
 * Created by amanda.shan on 2019/8/13.
 */
public class MemmerySessionManager extends SessionManagerAbstract {

    private ConcurrentHashMap<String, Session> sessionClientIdMap = new ConcurrentHashMap<>();

    private ConcurrentHashMap<Channel, Session> sessionChannelMap = new ConcurrentHashMap<>();


    @Override
    public ConcurrentHashMap<String, Session> getSessionClientIdMap() {
        return sessionClientIdMap;
    }

    @Override
    public ConcurrentHashMap<Channel, Session> getSessionChannelMap() {
        return sessionChannelMap;
    }


    @Override
    public synchronized void addSession(Session session) {

        sessionClientIdMap.put(session.getClientId(), session);
        if (session instanceof NettySession) {

            NettySession nettySession = (NettySession) session;
            sessionChannelMap.put(nettySession.getChannel(), session);
        }

        log.info("添加新用户：{}", session);
    }

    @Override
    public Session getSession(Channel channel) {
        return sessionChannelMap.get(channel);
    }

    @Override
    public Session getSession(String clientId) {
        return sessionClientIdMap.get(clientId);
    }


    @Override
    public synchronized void removeSession(Channel channel) {

        Session session = sessionChannelMap.get(channel);
        if (session != null) {
            removeSession(session);
        } else {
            log.info("用户不存在 关闭 channel：{}", channel);
        }
    }

    @Override
    public synchronized void removeSession(Session session) {

        if (session != null) {
            sessionClientIdMap.remove(session.getClientId());
        }

        if (session instanceof NettySession) {
            NettySession nettySession = (NettySession) session;
            sessionChannelMap.remove(nettySession.getChannel());

            nettySession.getChannel().close();
        }

        log.info("移除用户 session:{}", session);
    }
}
